package mylab.io.base.model.impl;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.base.Joiner;

import java.net.InetSocketAddress;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import mylab.io.base.model.Endpoint;
import mylab.utils.common.StringUtil;

@Getter
@Setter
@ToString
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class SocketEndpoint implements Endpoint {
    protected String ip;
    protected int port;

    public SocketEndpoint() {
    }

    public SocketEndpoint(int port) {
        this.ip = "0.0.0.0";
        this.port = port;
    }

    public SocketEndpoint(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }


    @JsonIgnore
    @EqualsAndHashCode.Include
    @Override
    public String getId() {
        return Joiner.on("/").join(ip, port);
    }

    @JsonIgnore
    public InetSocketAddress getAddress() {
        if (StringUtil.isEmpty(ip)) {
            return new InetSocketAddress(port);
        } else {
            return new InetSocketAddress(ip, port);
        }
    }

    @JsonIgnore
    public void setAddress(InetSocketAddress address) {
        if (address != null && !address.isUnresolved()) {
            this.ip = address.getHostString();
            this.port = address.getPort();
        }
    }

    @JsonIgnore
    public boolean isValidAddress() {
        return getAddress() != null && !getAddress().isUnresolved();
    }

}
